package fr.umlv.users;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.json.JSONArray;
import org.json.JSONObject;

import fr.umlv.authentication.SessionHandler;
import fr.umlv.metadata.WebServiceUtils;

// TODO: Auto-generated Javadoc
/**
 * The Class Permissions.
 */
public class Permissions {
	
	/** The url_permissions. */
	private static String url_permissions = "permissions/";
	
	/** The url_permissions_add. */
	private static String url_permissions_add = "permissions_add?";
	
	/** The url_permissions_del. */
	private static String url_permissions_del = "permissions_del?";
	
	/** The id params add. */
	private static String idParamsAdd = "noderef";
	
	/** The id params del. */
	private static String idParamsDel = "noderef";
	
	/** The user param. */
	private static String userParam = "user";
	
	/** The role param. */
	private static String roleParam = "role";
	
	
	/**
	 * Gets the permissions.
	 *
	 * @param cmisObject the cmis object
	 * @return the permissions
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws ParseException the parse exception
	 */
	public static Map<Person, List<String>> getPermissions(CmisObject cmisObject) throws IOException, ParseException{
		ResourceBundle bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow", SessionHandler.getLocale());
		HashMap<Person, List<String>> result = new HashMap<Person, List<String>>();
		String id = cmisObject.getId();
		id = id.replace(":/", "");
		JSONObject jsonObject = WebServiceUtils.getJsonService(SessionHandler.getUrlWebServices() + url_permissions + id);	
		JSONArray jsonArray = jsonObject.getJSONArray("permissions");
		for(int i=0; i<jsonArray.length();++i){
			String line = jsonArray.getString(i);
			String[] info_line = line.split(";");
			String username = info_line[1];
			String role = bundle.getString("role." + info_line[2]);
			UsersUtils userUtils = new UsersUtils(username);
			for(Person p : userUtils.getPersons()){
				if(p.getUserName().equals(username)){
					if(!result.containsKey(p)){
						ArrayList<String> roles = new ArrayList<String>();
						roles.add(role);
						result.put(p,roles);
					}else{
						result.get(p).add(role);
					}	
				}
			}
		}
		return result;
	}
	
	/**
	 * Update permissions.
	 *
	 * @param cmisObject the cmis object
	 * @param oldPermissions the old permissions
	 * @param newPermissions the new permissions
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws ParseException the parse exception
	 */
	public static void updatePermissions(CmisObject cmisObject, Map<Person, List<String>> oldPermissions, Map<Person, List<String>> newPermissions) throws IOException, ParseException{
		String id = cmisObject.getId();
		id = id.replace("workspace://SpacesStore/", "");
		
		//suppression des gars qui sont deja present dans la nouvelle hashmap
		for (Map.Entry<Person, List<String>> e : oldPermissions.entrySet()){
			Person p = e.getKey();
			List<String> roles = e.getValue();
			for(Map.Entry<Person, List<String>> e2 : newPermissions.entrySet()){
				Person p2 = e2.getKey();
				if(p2.getUserName().equals(p.getUserName())){
					for(String role : roles){
						String url = SessionHandler.getUrlWebServices() + url_permissions_del + idParamsDel + "=" + id + "&" + userParam + "=" + p.getUserName()+ "&" + roleParam + "=" + convertRoleName(role);
					    WebServiceUtils.getJsonService(url);
					}	
				}
			}
		}

		//Pour récupérer les clefs et les valeurs
		for (Map.Entry<Person, List<String>> e : newPermissions.entrySet()){
		    Person p = e.getKey();
		    List<String> roles = e.getValue();
		    for(String role : roles){
		    	String url = SessionHandler.getUrlWebServices() + url_permissions_add + idParamsAdd + "=" + id + "&" + userParam + "=" + p.getUserName() + "&" + roleParam + "=" + convertRoleName(role);
			    WebServiceUtils.getJsonService(url);
		    }	
		}
	
	}
	
	/**
	 * Gets the display names roles.
	 *
	 * @return the display names roles
	 */
	public static List<String> getDisplayNamesRoles(){
		List<String> result = new ArrayList<String>();
		ResourceBundle bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow", SessionHandler.getLocale());
		Enumeration<String> keys = bundle.getKeys();
		while(keys.hasMoreElements()){
			String key=keys.nextElement();
			if(key.startsWith("role.")){
				result.add(bundle.getString(key));
			}
		}
		Collections.sort(result);
		return result;
	}
	
	/**
	 * Convert role name.
	 *
	 * @param role the role
	 * @return the string
	 */
	public static String convertRoleName(String role){
		String result = "";
		ResourceBundle bundle;
		if(SessionHandler.getLocale().equals(Locale.ENGLISH)){
			return role;
		}else{
			bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow",SessionHandler.getLocale());
			Enumeration<String> keys = bundle.getKeys();
			while(keys.hasMoreElements()){
				String key = keys.nextElement();
				//on tente de recuperer la cle utilisee pour ce role
				if(key.startsWith("role.")){
					if(bundle.getString(key).equals(role)){
						bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow",Locale.ENGLISH);
						result = bundle.getString(key);
					}
				}
			}
		}
		return result;	
	}
	
	/**
	 * Delete permissions.
	 *
	 * @param cmisObject the cmis object
	 * @param userName the user name
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws ParseException the parse exception
	 */
	public static void deletePermissions(CmisObject cmisObject, String userName) throws IOException, ParseException{
		String id = cmisObject.getId();
		id = id.replace("workspace://SpacesStore/", "");
		Map<Person, List<String>> permissions = getPermissions(cmisObject);
		for (Map.Entry<Person, List<String>> e : permissions.entrySet()){
			Person p = e.getKey();
		    List<String> roles = e.getValue();
		    if(p.getUserName().equals(userName)){
		    	for(String tmpRole : roles){
		    		String url = SessionHandler.getUrlWebServices() + url_permissions_del + idParamsDel + "=" + id + "&" + userParam + "=" + p.getUserName()+ "&" + roleParam + "=" + convertRoleName(tmpRole);
				    WebServiceUtils.getJsonService(url);
		    	}    	
		    }
		}
	}
	
	
	/**
	 * Gets the permissions for user.
	 *
	 * @param personPermissions the person permissions
	 * @param userName the user name
	 * @return the permissions for user
	 */
	public static List<String> getPermissionsForUser(Map<Person, List<String>> personPermissions, String userName){
		for (Map.Entry<Person, List<String>> e : personPermissions.entrySet()){
		    Person p = e.getKey();
		    if(p.getUserName().equals(userName)){
		    	return e.getValue();
		    }
		}
		return new ArrayList<String>();
	}
}
